package com.hjh.netty.elect.demo4;


import com.hjh.netty.elect.util.NumberDataConvertUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Pmc350Encoder extends MessageToByteEncoder<Pmc350ProtocolModel> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Pmc350ProtocolModel msg, ByteBuf out) throws Exception {
        StringBuilder sendCmd = new StringBuilder();
        //包头，固定F9
        sendCmd.append(msg.getPacketHeader());
        //包标识
        sendCmd.append(msg.getPacketFlag());
        //设备id长度，转为16进制
        String deviceIdCodeLengthstr = NumberDataConvertUtils.decimalString2hexString(String.valueOf(msg.getDeviceIdCodeLength()));
        sendCmd.append(deviceIdCodeLengthstr);
        //设备id
        sendCmd.append(msg.getDeviceIdCode());
        //payload长度，转为16进制
        String payLoadLengthstr = NumberDataConvertUtils.decimalString2hexString(String.valueOf(msg.getPayLoadLength()));
        sendCmd.append(payLoadLengthstr);
        //payload检验
        sendCmd.append(msg.getPayLoadVerifyTotal());
        //头结尾，固定F9
        sendCmd.append(msg.getPacketHeaderEnd());
        //payload内容
        sendCmd.append(msg.getPayLoad());
        log.info("数据编码成功{}", sendCmd);
        //out.writeBytes(DataConvertUtils.hexString2Bytes(sendCmd.toString()));
        out.writeBytes(ByteCastUtil.hexStringToBytes(String.valueOf(sendCmd)));
    }

}
